package main

import (
	"context"
	"fmt"
	"gin-init/configs"
	"gin-init/internal/server"
	"gin-init/pkg/logger"
	"gin-init/pkg/shutdown"
	"runtime"
	"time"
)

func main() {
	var consoleStr = make([]string, 3)
	consoleStr[0] = fmt.Sprintf("Project：%c[32m%s%c[0m", 0x1B, configs.ProjectName, 0x1B)
	consoleStr[1] = fmt.Sprintf("GoVersion：%c[32m%s%c[0m", 0x1B, runtime.Version(), 0x1B)
	consoleStr[2] = fmt.Sprintf("Listen：%c[32m%d%c[0m", 0x1B, configs.ProjectPort, 0x1B)
	for _, str := range consoleStr {
		fmt.Println(str)
	}

	//注册关闭函数
	ctx, cancel := context.WithCancel(context.Background())
	//生成http服务
	ser, cron, err := server.RunServer(ctx)
	if err != nil {
		panic(err)
	}
	//处理服务暂停函数
	shutdown.NewHook().Close(
		func() {
			_ = logger.Sync()
		},
		func() {
			cancel()
		},
		func() {
			ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
			defer cancel()
			//进程结束，停止定时任务
			if cron != nil {
				cron.Stop()
			}
			// 关闭 server
			if err = ser.Shutdown(ctx); err != nil {
				logger.Errorw("server shutdown fail", "error", err)
			}
		},
	)
}
